//authorization.js
const app = getApp()

Page({
  data: {
    winWidth: 0,
    winHeight: 0,
    emailCode: '',
    mailboxId: '',
    isSubmit: true
  },
  onLoad: function () {
    var that = this;
    var data = {
      userId: app.globalData.wxUserId
    }
    // 获取授权码信息
    app.http.post('/wechat/findMailboxInfo',data).then(res =>{
      if(res.status == '200') {
        if(res.data){
          var isSubmit = true
          let changeCode = ""
          if(res.data.emailCode != null && res.data.emailCode != ''){
            isSubmit = false
            let code = res.data.emailCode
            changeCode = code.replace(/\s/g,'').replace(/[^\w\.\/]/g,'').replace(/(\w{4})(?=\w)/g,"$1 ")
          }
          that.setData({
            isSubmit: isSubmit,
            emailCode: changeCode,
            mailboxId: res.data.mailboxId
          })
        }
      }
    })
    /**
     * 获取当前设备的宽高
     */
    that.setData({
      winWidth: app.globalData.winWidth,
      winHeight: app.globalData.winHeight
    });
  },
  doLogin: function(e) {
    var that = this
    var code = e.detail.value.authorizationCode.replace(/\s+/g, '')
    if(code != null && code != ''){
      var data = {
        mailboxId: that.data.mailboxId,
        emailCode: code
      }
      wx.showLoading({
        title: '登录中...',
      })
      app.http.post('/wechat/updateEmailCode',data).then(res =>{
        wx.hideLoading()
        if(res.status == '200') {
          wx.switchTab ({
            url: '/pages/index/index'
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none"
          })
        }
      })
    } else {
      wx.showToast({
        title: '请输入正确授权码',
        icon: "none"
      })
    }
  },
  codeJude: function(e) { //输入授权码事件
    var that = this
    if (e.detail.value.length > 0) {
      let code = e.detail.value
      let changeCode = code.replace(/\s/g,'').replace(/[^\w\.\/]/g,'').replace(/(\w{4})(?=\w)/g,"$1 ")
      that.setData({isSubmit: false,emailCode: changeCode})
    } else {
      that.setData({isSubmit: true,emailCode: e.detail.value})
    }
  }
})
